<?php


namespace App\Http\Services;


use App\Model\Project;

class ProjectService extends BaseService
{
    /**
     * @param array $params
     * @return Project
     */
    public function create(array $params = []) :Project
    {
        return Project::create($params);
    }

    /**
     * @param int $limit
     * @param int $size
     * @return array
     */
    public function getAll($limit = 0, $size = 0) :array
    {
        if ($limit > 0 && $size > 0) {
            $projects = Project::limit($limit)->take($size)->get()->toArray();
        } else {
            $projects = Project::all()->toArray();
        }
        return $projects;
    }

    /**
     * @param int $projectId
     * @param int $userId
     * @param array | string $with
     * @return Project|Project[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     */
    public function get(int $projectId, int $userId, $with = [])
    {
       return Project::with($with)->where("user_id", $userId)->find($projectId);
    }

    /**
     * @param int $id
     * @param array $params
     * @return bool
     */
    public function update(int $id, array $params = []) :bool
    {
        $project = Project::find($id);
        return $project->update($params);
    }

    /**
     * @param int $id
     * @return bool
     */
    public function delete(int $id):bool
    {
        try {
            $project =  Project::find($id);
            if($project->tasks->isNotEmpty()) {
                return false;
            }
            return $project->delete();
        } catch (\Exception $e) {
            \Log::error($e->getMessage());
            return false;
        }
    }
}